package com.haoyeteng.sxbd.modular.business.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.haoyeteng.sxbd.core.base.model.ResponseResult;
import com.haoyeteng.sxbd.core.constant.DeleteFlag;
import com.haoyeteng.sxbd.core.util.ToolUtil;
import com.haoyeteng.sxbd.modular.business.dao.ZbzhFileMapper;
import com.haoyeteng.sxbd.modular.business.model.ZbzhFile;
import com.haoyeteng.sxbd.modular.business.service.IZbzhFileService;
import com.haoyeteng.sxbd.modular.common.service.IUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.*;
import java.util.zip.InflaterInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * <p>
 * 坐标转换文件表 服务实现类
 * </p>
 *
 * @author haoyeteng123
 * @since 2019-10-27
 */
@Service
@Transactional
public class ZbzhFileServiceImpl extends ServiceImpl<ZbzhFileMapper, ZbzhFile> implements IZbzhFileService {
    @Autowired
    private IUploadService uploadService;

    @Override
     public ResponseResult addZbzhFiles( MultipartFile uploadImage,int size,ResponseResult<Object> result){
         String fileName = uploadImage.getOriginalFilename();
         if (!fileName.matches("(.*)\\.(zip|txt|json|csv|shp|shx|dbf|ZIP|TXT|JSON|CSV|SHP|SHX|DBF)$")) {
             result.setCode(-1);
             result.setMsg("上传文件格式不正确,请上传后缀名为（zip、txt、json、csv、shp、shx、dbf）格式的文件，不区分大小写");
             return result;
         } else if (size > 26214400) {
             result.setCode(-1);
             result.setMsg("上传的文件不能大于25M");
             return result;
         } else {
             try {
                 Map<String, Object> map = new HashMap<String, Object>();
                 if (fileName.matches("(.*)\\.(zip|ZIP)$")) {
                     // 得到MultipartFile文件
                     MultipartFile multipartFile = uploadImage;
                     // 输出文件的新name 就是指上传后的文件名称
                     System.out.println("getName:"+multipartFile.getName());
                     // 输出源文件名称 就是指上传前的文件名称
                     System.out.println("Oriname:"+multipartFile.getOriginalFilename());
                     StringBuilder stringBuilder = new StringBuilder();
                     ZipInputStream zs = null;
                     try {
                         zs = new ZipInputStream(multipartFile.getInputStream(), Charset.forName("GBK"));
                         ZipEntry ze;
                         while((ze = zs.getNextEntry()) != null){
                             //是文件夹
                             if (ze.isDirectory()) {
                                 System.out.println("是文件夹,不处理");
                             }else {
                                 //是文件
                                 long entrySize = ze.getSize();
                                 // 获取当前条目的字节数组
                                 byte[] data = this.getByte(zs);
                                 // 把当前条目的字节数据转换成Inputstream流
                                 InputStream is = new ByteArrayInputStream(data);

                                 String[] names = ze.getName().split("/");
                                 String entryName = names[names.length-1];

                                 if (!entryName.matches("(.*)\\.(txt|json|csv|shp|shx|dbf|TXT|JSON|CSV|SHP|SHX|DBF)$")) {
                                     result.setCode(-1);
                                     result.setMsg("压缩包内文件格式不正确,请上传后缀名为(txt、json、csv、shp、shx、dbf）格式的文件，不区分大小写");
                                     return result;
                                 }

                                 //获取zip包中的每一个entry
                                 Long time = System.currentTimeMillis();
                                 int random = (int) (Math.random() * 10000);
                                 String newFileName = time.toString() + random + entryName.substring(entryName.lastIndexOf("."));
                                 String fileid = uploadService.addFile(is, multipartFile.getContentType(), newFileName);
                                 stringBuilder.append(fileid).append(",");

                                 ZbzhFile zbzhFile = new ZbzhFile();
                                 zbzhFile.setFileId(fileid);
                                 zbzhFile.setFileName(entryName);
                                 zbzhFile.setFileSize((float)(entrySize));
                                 Date date = new Date();
                                 zbzhFile.setCreateTime(date);
                                 zbzhFile.setUpdateTime(date);
                                 zbzhFile.setFlag(DeleteFlag.OK.getCode());
                                 this.baseMapper.insert(zbzhFile);

                                 is.close();
                             }

                         }

                         zs.close();
                         if (ToolUtil.isNotEmpty(stringBuilder.toString())) {
                             stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                         }

                         //ZIP插入到mongodb中 作为回显
                         String fileidZip = addFileToMongodb(uploadImage, fileName, map);
                         map.put("fileIds", stringBuilder.toString());

                     }catch(Exception e) {
                         throw new RuntimeException("解压出现错误", e);
                     } finally {
                         if(zs != null){
                             try {
                                 zs.close();
                             } catch (IOException e) {
                                 e.printStackTrace();
                             }
                         }
                     }

                 } else {
                     //直接插入到文件表中
                     String fileid = addFileToMongodb(uploadImage, fileName, map);

                     ZbzhFile zbzhFile = new ZbzhFile();
                     zbzhFile.setFileId(fileid);
                     zbzhFile.setFileName(fileName);
                     zbzhFile.setFileSize((float)(size));
                     Date date = new Date();
                     zbzhFile.setCreateTime(date);
                     zbzhFile.setUpdateTime(date);
                     zbzhFile.setFlag(DeleteFlag.OK.getCode());
                     this.baseMapper.insert(zbzhFile);
                 }
                 String fileIdsVo = map.get("fileIds").toString();
                 String[] fileIdsArr = fileIdsVo.split(",");

                 //校验文件 是否3个都在
//                 List<String> zbzhFilesName = null;
//                 List<ZbzhFile> zbzhFiles = null;
//                 if (ToolUtil.isNotEmpty(fileIdsArr)) {
//                     zbzhFiles = this.baseMapper.selectBatchIds(Arrays.asList(fileIdsArr));
//                 }
//                 if (ToolUtil.isNotEmpty(zbzhFiles) && zbzhFiles.size() >1) {
//                     for (ZbzhFile zbzhFile : zbzhFiles) {
//                         zbzhFilesName.add(zbzhFile.getFileName());
//                     }
//                     if (ToolUtil.isNotEmpty(zbzhFilesName)) {
//
//                     }
//                 }

                 result.setData(map);
                 result.setCode(0);
                 result.setMsg("操作成功");
             } catch (Exception e) {
                 e.printStackTrace();
                 throw new RuntimeException(e);
             }
         }
        return result;
     }


    private String addFileToMongodb(MultipartFile uploadImage, String fileName, Map<String, Object> map) throws IOException {
        Long time = System.currentTimeMillis();
        int random = (int) (Math.random() * 10000);
        String newFileName = time.toString() + random + fileName.substring(fileName.lastIndexOf("."));
        String fileid = uploadService.addFile(uploadImage, newFileName);
        map.put("fileid", fileid);
        map.put("fileIds", fileid);
        map.put("filename", fileName);
        return fileid;
    }

    /**
     * 获取条目byte[]字节
     * @param zis
     * @return
     */
    private byte[] getByte(InflaterInputStream zis) {
        try {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] temp = new byte[1024];
            byte[] buf = null;
            int length = 0;

            while ((length = zis.read(temp, 0, 1024)) != -1) {
                bout.write(temp, 0, length);
            }

            buf = bout.toByteArray();
            bout.close();
            return buf;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}
